/**
 * @Description:摄像头控件
 * 
 * 属性
 * @param historystarttime 历史播放开始时间,单位是秒
 * @param historyendtime 历史播放结束时间,单位是秒
 * @param hidedel 为"true"时不显示删除按钮
 * @param notimetxt 为"true"时没有剩余历史回放的时间
 * @param hidetimeline 为"true"时不显示进度条，但是全屏时显示进度条
 * @param hideslowbtn 为"true"时不显示慢放按钮，但是全屏时显示慢放按钮
 * 
 * @function setPlayInfo 设置播放信息
 * 
 * 
 * @Copyright: 成都和为科技有限公司 2016
 */
function Device() {
}

Device.inherit(Control);

Device.prototype.init = function() {
    Device.base.init.call(this);
}

/** 慢放参数 */
Device.slow_params = [ 3, 4, 5, 6, 7, 8, 9 ];
/** 慢放的速度和正常速度的比例 */
Device.slow_speeds = [ 0.25, 0.5, 1, 2, 4, 8, 16 ];
/** 保存所有的视频对象 */
Device.all_devices = {};

/**
 * 创建设备控件
 */
Device.prototype.create = function() {
    this._videoid = Math.uuid() + "_video";
    var _html = '<div class="video-comp" videoid="' + this._videoid + '" tabindex="1">';
    _html += '<div class="video-title">';
    _html += '  <span class="video-name"/>';
    _html += '  <span class="video-del" title="删除" style=\"cursor:pointer;z-index:999\"/>';
    _html += '</div>';
    _html += '<div class="video-content">';
    _html += '  <object type="application/x-streammediaplugin"></object>';
    _html += '</div>';
    _html += '  <div class="control-direction control-zs"><div class="control-zs-btn"/></div>';
    _html += '  <div class="control-direction control-s"><div class="control-sb"><div class="control-s-btn"/></div></div>';
    _html += '  <div class="control-direction control-ys"><div class="control-ys-btn"/></div>';
    _html += '  <div class="control-direction control-z"><div class="control-zb"><div class="control-z-btn"/></div></div>';
    _html += '  <div class="control-direction control-y"><div class="control-yb"><div class="control-y-btn"/></div></div>';
    _html += '  <div class="control-direction control-zx"><div class="control-zx-btn"/></div>';
    _html += '  <div class="control-direction control-yx"><div class="control-yx-btn"/></div>';
    _html += '  <div class="control-direction control-x"><div class="control-xb"><div class="control-x-btn"/></div></div>';
    _html += '<div class="video-bottom" style="z-index: 999">';
    _html += '  <div class="video-bottom-left">';
    _html += '    <span class="play" title="播放"></span>';
    _html += '    <span class="video-close" title="暂停"></span>';
    _html += '  </div>';
    _html += '  <div class="video-bottom-right-full">';
    _html += '    <span class="full" title="全屏"></span>';
    _html += '  </div>';
    _html += '  <div class="video-bottom-right">';
    _html += '    <span class="nofull" title="关闭全屏"></span>';
    _html += '    <span class="sound" title="设置静音"></span>';
    _html += '    <span class="nosound" title="取消静音"></span>';
    _html += '    <span class="print-record" title="截图"></span>';
    _html += '    <span class="start-record" title="录像"></span>';
    _html += '    <span class="stop-record" title="录像中"></span>';
    _html += '    <span class="slow" title="慢放">慢放</span>';
    _html += '    <span class="control" title="云台控制"></span>';
    _html += '    <span class="timetxt" title="时间"></span>';
    _html += '    <span class="face-on" title="人脸识别"></span>';
    _html += '    <span class="face-off" title="识别中"></span>';
    _html += '  </div>';
    _html += '  <div class="video-bottom-middle">';
    _html += '    <div id="progress" class="progress progress-nofull" title="进度条">';
    _html += '      <div class="progress-bar" role="progressbar" aria-valuemin="0" aria-valuemax="100"/>';
    _html += '      <div class="timeline"/>';
    _html += '      <div class="timebtn"/>';
    _html += '    </div>';
    _html += '  </div>';
    _html += '</div>';
    _html += '<div class="video-slow-bottom">';
    _html += '  <div class="video-slow-right">';
    _html += '    <div class="video-slow-toolbar" title="播放倍率">';
    _html += '      <div class="slowline"/>';
    _html += '      <div class="slowbtn"/>';
    _html += '      <div class="timenum timenum-first">1/4</div>';
    _html += '      <div class="timenum timenum-two">1/2</div>';
    _html += '      <div class="timenum timenum-other">1</div>';
    _html += '      <div class="timenum timenum-other">2</div>';
    _html += '      <div class="timenum timenum-other">4</div>';
    _html += '      <div class="timenum timenum-other">8</div>';
    _html += '      <div class="timenum timenum-last">16</div>';
    _html += '    </div>';
    _html += '  </div>';
    _html += '  <div class="video-slow-text" title="播放倍率">播放倍率</div>';
    _html += '</div>';
    if(this.getAttribute().hasframe == "true"){//增加是否需要增加iframe的条件值，现目前主要针对3D页面有2个firbreash插件，视屏进行全屏不能正常显示
        _html += '<iframe frameborder="0" width="100%" height="100%" style="position: absolute;left: 0;top: 0;background-color: transparent;"></iframe>';
    }
    _html += '</div>';
    this._html = $(_html)[0];
    this.plugin = $('object', this._html)[0];
}

/**
 * 初始化摄像头页面
 */
Device.prototype.initLoad = function() {
    if (!$.fn.draggable) {
        this.loadCSSFile("/public.common/webapi/common/autocomplete/jquery.autocomplete.css");
        this.loadScriptFile("/public.common/webapi/common/jqueryui/jquery-migrate-1.2.1.js");
        this.loadScriptFile("/public.common/webapi/common/jqueryui/jquery.ui.core.js");
        this.loadScriptFile("/public.common/webapi/common/jqueryui/jquery.ui.widget.js");
        this.loadScriptFile("/public.common/webapi/common/jqueryui/jquery.ui.mouse.js");
        this.loadScriptFile("/public.common/webapi/common/jqueryui/jquery.ui.draggable.js");
    }
    
    this.playInfo = $('.video-content', this._html)[0];
    this.playInfo.sessionid = "heweisessionid";
    this.playInfo.isplay = "stop";
    this.playInfo.isrecord = "stop";
    this.playInfo.sound = "nosound";
    this.playInfo.ishistory = "stop";
    this.playInfo.historyalltime = 3 * 60 * 60;// 历史播放总时间
    this.playInfo.historynotdragtime = 6 * 60;// 不能历史播放的时间
    this.playInfo.historydefaultnotdragtime = 6 * 60;// 不能历史播放的时间
    this.playInfo.historystarttime = 0;// 历史播放开始时间
    this.playInfo.historydragtime = 0;// 历史播放拖拽时间
    this.playInfo.isfull = false;
    this.playInfo.slowindex = 2;
    this.playInfo.faceNum = false;
    this.setPlayInfo(this.getAttribute());

    var $html = this._html;
    var othis = this;

    $($html).bind("keydown", function(event) {
        if(event.keyCode == 27 && othis.playInfo.isfull){
            othis.nofull();
        }
    });
    
    $(".video-del", $html).bind("click", function() {
        othis.delVideo();
    });

    $(".play", $html).bind("click", function() {
        othis.play();
    });

    $(".video-close", $html).bind("click", function() {
        othis.pause();
    });

    $(".full", $html).bind("click", function() {
        othis.full();
    });

    $(".nofull", $html).bind("click", function() {
        othis.nofull();
    });

    $(".sound", $html).bind("click", function() {
        othis.nosound();
    });

    $(".nosound", $html).bind("click", function() {
        othis.sound();
    });
    
    $(".face-on", $html).bind("click", function() {
        othis.faceOn();
    });
    
    $(".face-off", $html).bind("click", function() {
        othis.faceOff();
    });
    
    $(".start-record", $html).bind("click", function() {
        othis.startRecord();
    });

    $(".stop-record", $html).bind("click", function() {
        othis.stopRecord();
    });

    $(".print-record", $html).bind("click", function() {
        othis.printRecord();
    });

    $(".slow", $html).bind("click", function() {
        othis.clickSlowBtn();
    });
    
    $(".control", $html).bind("click", function() {
        othis.clickConsoleBtn();
    });
    
    $(".control-zs-btn", $html).bind("mousedown", function() {
        othis.controlMove("LEFTUP");
        Device.log("云台：左上转");
    }).bind("mouseup", function() {
        othis.controlMove("LEFTUPSTOP");
        Device.log("云台：左上转停止");
    });
    $(".control-s-btn", $html).bind("mousedown", function() {
        othis.controlMove("UP");
        Device.log("云台：上转");
    }).bind("mouseup", function() {
        othis.controlMove("UPSTOP");
        Device.log("云台：上转停止");
    });
    $(".control-ys-btn", $html).bind("mousedown", function() {
        othis.controlMove("RIGHTUP");
        Device.log("云台：右上转");
    }).bind("mouseup", function() {
        othis.controlMove("RIGHTUPSTOP");
        Device.log("云台：右上转停止");
    });
    $(".control-z-btn", $html).bind("mousedown", function() {
        othis.controlMove("LEFT");
        Device.log("云台：左转");
    }).bind("mouseup", function() {
        othis.controlMove("LEFTSTOP");
        Device.log("云台：左转停止");
    });
    $(".control-y-btn", $html).bind("mousedown", function() {
        othis.controlMove("RIGHT");
        Device.log("云台：右转");
    }).bind("mouseup", function() {
        othis.controlMove("RIGHTSTOP");
        Device.log("云台：右转停止");
    });
    $(".control-zx-btn", $html).bind("mousedown", function() {
        othis.controlMove("LEFTDOWN");
        Device.log("云台：左下转");
    }).bind("mouseup", function() {
        othis.controlMove("LEFTDOWNSTOP");
        Device.log("云台：左下转停止");
    });
    $(".control-x-btn", $html).bind("mousedown", function() {
        othis.controlMove("DOWN");
        Device.log("云台：下转");
    }).bind("mouseup", function() {
        othis.controlMove("DOWNSTOP");
        Device.log("云台：下转停止");
    });
    $(".control-yx-btn", $html).bind("mousedown", function() {
        othis.controlMove("RIGHTDOWN");
        Device.log("云台：右下转");
    }).bind("mouseup", function() {
        othis.controlMove("RIGHTDOWNSTOP");
        Device.log("云台：右下转停止");
    });
    $(".control-fy-btn", $html).bind("click", function() {
        othis.controlMove("RESET");
        Device.log("云台：复位");
    });
    
    $("#progress", $html).bind("click", function(e) {
        var $this = $(this);
        var _allTime = othis.playInfo.historyalltime;
        var _drag_width = e.pageX - $this.offset().left;
        var _proportion = _drag_width / $this.width();

        $(".progress-bar", $this).width(_proportion * 100 + "%");

        var _timebtn = $(".timebtn", $this);
        _timebtn.offset({
            left : e.pageX - _timebtn.width() / 2
        });

        var startTime = othis.playInfo.historystarttime;
        if (othis.playInfo.ishistory == "stop") {
            startTime = Device.getNowTime() - _allTime;
        }
        var dragTime = Math.round(_allTime * _proportion) + startTime;
        othis.startHistory(startTime, dragTime);
    });
}

/**
 * 删除摄像头
 */
Device.prototype.delVideo = function() {
    var _video = this._html;
    this.stop();
    
    try {
        this.playInfo.removeChild(this.plugin);
        _video.parentNode.removeChild(_video);
    }catch (e) {
        Device.log("销毁元素失败");
    }
	application.getHandleClass().postMessage({"id":"MSG_CREATE_GETFACENUM"});
}

/**
 * 删除摄像头
 * 
 * @param video 控件js对象
 */
Device.delVideoByObj = function(video) {
    var _plugin = $(video).find("object")[0];
    var _playInfo = $(video).find(".video-content")[0];
    var _video_comp = $(video)[0];
    if (!_playInfo) return;
    if (_playInfo.ishistory != "stop") {
        try {
            _plugin.stopHistoryPlayer();
            Device.log("停止历史回放：摄像头名称：" + _playInfo.titlename +" -- 地址："+ _playInfo.playurl);
        } catch (e) {
            Device.log("暂停历史回放失败");
        }
    }
    if (_playInfo.isplay != "stop") {
        try {
            _plugin.stopVideoPlayer();
            Device.log("停止实时播放：摄像头名称：" + _playInfo.titlename +" -- 地址："+ _playInfo.playurl);
        } catch (e) {
            Device.log("暂停实时播放失败");
        }
    }

    try {
        _playInfo.removeChild(_plugin);
        _video_comp.parentNode.removeChild(_video_comp);
    }catch (e) {
        Device.log("销毁元素失败");
    }
    application.getHandleClass().postMessage({"id":"MSG_CREATE_GETFACENUM"});
}


/**
 * 得到摄像头句柄
 */
Device.prototype.getWndHandle = function() {
   return this.plugin.getWndHandle();
}

/**
 * 播放
 */
Device.prototype.play = function() {
    
    if (this.playInfo.ishistory == "pause") {
        this.restartHistory();
        return;
    }

    if (this.playInfo.ishistory == "start") {
        this.stopHistory();
    }

    if (this.playInfo.isplay == "stop") {
        this.clickSlowBtn(true);
        $(".slow", this._html).hide();
        $(".stop-record", this._html).hide();
        $(".start-record", this._html).show();
        $(".sound", this._html).hide();
        $(".nosound", this._html).show();
        this.startVideo();
    }

    var _progress = $('#progress', this._html);
    var _timebtn = $(".timebtn", this._html);
    $(".progress-bar", this._html).width("100%");
    _timebtn.offset({
        left : _progress.width() + _progress.offset().left - _timebtn.width() / 2
    });
    $(".timetxt", this._html).text("").hide();

    if (this.playInfo.changeTimeInterval) {
        clearInterval(this.playInfo.changeTimeInterval);
    }

    $(".slowbtn", this._html).css("left", "84px");
    this.playInfo.historystarttime = 0;
    this.playInfo.historydragtime = 0;
    this.playInfo.slowindex = 2;
    application.getHandleClass().postMessage({"id":"MSG_CREATE_GETFACENUM"});
}

/**
 * 停止播放
 */
Device.prototype.stop = function() {
    if (this.playInfo.ishistory != "stop") {
        this.stopHistory();
    }
    if (this.playInfo.isplay != "stop") {
        this.stopVideo();
    }
}

/**
 * 暂停
 */
Device.prototype.pause = function() {
    // 暂停历史回放
    if (this.playInfo.ishistory == "start") {
        this.pauseHistory();
        return;
    }

    if (this.playInfo.ishistory == "pause") {
        this.stopHistory();
    }

    if (this.playInfo.isplay = "start") {
        this.stopVideo();
    }
}

/**
 * 开始实时播放方法
 */
Device.prototype.startVideo = function() {
    if (!this.playInfo.playurl) {
        return;
    }

    $(".play", this._html).hide();
    $(".video-close", this._html).show();

    try {
    	var that = this;
    	//setTimeout(function(){
            this.plugin.startVideoPlayer(that.playInfo.playurl, that.playInfo.sessionid);
    	//}, 1000);
        
        this.playInfo.isplay = "start";
        Device.log("开始实时播放：摄像头名称：" + this.playInfo.titlename +" -- 地址："+ this.playInfo.playurl);
        this.saveLog({
            title : "视频信息",
            method : "实时播放",
            playUrl : this.playInfo.playurl
        });
    } catch (e) {
        Device.log("开始实时播放失败");
    }
}

/**
 * 停止实时播放方法
 */
Device.prototype.stopVideo = function() {
    if (!this.playInfo.playurl) {
        return;
    }
    try {
        this.playInfo.isplay = "stop";
        $(".play", this._html).show();
        $(".video-close", this._html).hide();
        this.plugin.stopVideoPlayer();
        Device.log("停止实时播放：摄像头名称：" + this.playInfo.titlename +" -- 地址："+ this.playInfo.playurl);
    } catch (e) {
        Device.log("停止实时播放失败");
    }
}

/**
 * 开始历史回放方法
 */
Device.prototype.startHistory = function(startTime, dragTime) {
    if (!this.playInfo.playurl) {
        return;
    }

    var endTime = startTime + this.playInfo.historyalltime - this.playInfo.historynotdragtime;

    // 停止实时播放
    if (this.playInfo.isplay == "start") {
        this.stopVideo();
    }

    if (startTime >= endTime) {
        this.stopHistory();
        this.startVideo();
        return;
    }

    // 没有历史播放则开始历史播放，然后再拖拽到dragTime开始播放
    if (this.playInfo.ishistory == "stop") {
        this.playInfo.ishistory = "start";

        try {
            this.plugin.startHistoryPlayer(this.playInfo.playurl, this.playInfo.sessionid, startTime + "", endTime + "");
            this.playInfo.historystarttime = parseInt(startTime);
            this.playInfo.historydragtime = parseInt(dragTime);
            
            var _stime = DateTime.getDateTimeSecondsString(new Date(this.playInfo.historystarttime * 1000));
            var _etime = DateTime.getDateTimeSecondsString(new Date(endTime * 1000));
            Device.log("开始历史播放，从" + _stime + "开始到" + _etime + "结束");
            
            $(".sound", this._html).hide();
            $(".nosound", this._html).show();
            $(".stop-record", this._html).hide();
            $(".start-record", this._html).show();
            if(this.playInfo.hideslowbtn == true){
                if(this.playInfo.isfull == true){
                    $(".slow", this._html).show();
                }else{
                    $(".slow", this._html).hide();
                }
            }else{
                $(".slow", this._html).show();
            }
            
            this.saveLog({
                title : "视频信息",
                method : "历史播放",
                playUrl : this.playInfo.playurl
            });
        } catch (e) {
            Device.log("开始历史播放失败");
        }
    }

    $(".video-close", this._html).show();
    $(".play", this._html).hide();

    // 当开始历史回放后才开始拖拽播放
    var that = this;
    if (that.plugin.isHisPlay == "true") {
        that.dragHistory(dragTime);
        that.changeTime(1000 / Device.slow_speeds[that.playInfo.slowindex]);
    } else {
        var _interval = setInterval(function() {
            if (that.plugin.isHisPlay == "true") {
                clearInterval(_interval);
                that.dragHistory(dragTime);
                that.changeTime(1000 / Device.slow_speeds[that.playInfo.slowindex]);
            }
        }, 500);
    }
}

/**
 * 拖拽历史回放方法
 */
Device.prototype.dragHistory = function(dragTime) {
    var changeTimeInterval = this.playInfo.changeTimeInterval;
    if (changeTimeInterval) {
        clearInterval(changeTimeInterval);
    }

    this.playInfo.historydragtime = parseInt(dragTime);

    // 拖拽到最后6分钟则实时播放
    if (this.playInfo.historystarttime + this.playInfo.historyalltime - this.playInfo.historydragtime < this.playInfo.historynotdragtime) {
        this.stopHistory();
        this.play();
        return;
    }

    $(".timetxt", this._html).show();

    try {
        this.plugin.dragHistoryPlayer(dragTime + "");
        var _time = DateTime.getDateTimeSecondsString(new Date(this.playInfo.historydragtime * 1000));
        Device.log("历史播放，"+_time);
    } catch (e) {
        Device.log("拖拽播放失败");
    }
}

/**
 * 停止历史回放方法
 */
Device.prototype.stopHistory = function() {
    if (!this.playInfo.playurl) {
        return;
    }

    try {
        this.playInfo.ishistory = "stop";
        this.plugin.stopHistoryPlayer();
        $(".video-close", this._html).show();
        $(".play", this._html).hide();
        Device.log("停止历史播放：摄像头名称：" + this.playInfo.titlename + " -- 地址：" + this.playInfo.playurl);
    } catch (e) {
        Device.log("停止历史播放失败");
    }
}

/**
 * 暂停播放历史回放方法
 */
Device.prototype.pauseHistory = function() {
    if (!this.playInfo.playurl) {
        return;
    }

    try {
        this.plugin.pauseHistoryPlayer();
        $(".video-close", this._html).hide();
        $(".play", this._html).show();
        this.playInfo.ishistory = "pause";
        Device.log("暂停历史播放：摄像头名称：" + this.playInfo.titlename +" -- 地址："+ this.playInfo.playurl);
    } catch (e) {
        Device.log("暂停历史播放失败");
    }
}

/**
 * 恢复播放历史回放方法
 */
Device.prototype.restartHistory = function() {
    if (!this.playInfo.playurl) {
        return;
    }

    try {
        this.plugin.restartHistoryPlayer();
        $(".video-close", this._html).show();
        $(".play", this._html).hide();
        this.playInfo.ishistory = "start";
        Device.log("重新开发历史回放：摄像头名称：" + this.playInfo.titlename +" -- 地址："+ this.playInfo.playurl);
    } catch (e) {
        Device.log("重新开发历史回放失败");
    }
}

/**
 * 视频截图方法
 */
Device.prototype.printRecord = function() {
    if (!this.playInfo.playurl) {
        return;
    }

    try {
        this.plugin.screenShortVideo();
        this.saveLog({
            title : "视频信息",
            method : "视频截图",
            playUrl : this.playInfo.playurl
        });
    } catch (e) {
        Device.log("截屏失败");
    }
}

/**
 * 打开声音方法
 */
Device.prototype.sound = function() {
    if (!this.playInfo.playurl) {
        return;
    }
    
    try {
        this.plugin.openSound();
        $(".sound", this._html).show();
        $(".nosound", this._html).hide();
        this.playInfo.sound = "sound";
    } catch (e) {
        Device.log("打开声音失败");
    }
}

/**
 * 关闭声音方法
 */
Device.prototype.nosound = function(src) {
    if (!this.playInfo.playurl) {
        return;
    }
    
    try {
        this.plugin.closeSound();
        $(".sound", this._html).hide();
        $(".nosound", this._html).show();
        this.playInfo.sound = "nosound";
    } catch (e) {
        Device.log("关闭声音失败");
    }
}

/**
 * 开始录像方法
 */
Device.prototype.startRecord = function() {
    if (!this.playInfo.playurl) {
        return;
    }

    try {
        this.plugin.startRecordVideo();
        
        $(".start-record", this._html).hide();
        $(".stop-record", this._html).show();
        
        this.playInfo.isrecord = "start";
        
        this.saveLog({
            title : "视频信息",
            method : "视频录像",
            playUrl : this.playInfo.playurl
        });
    } catch (e) {
        Device.log("录像失败");
    }
}

/**
 * 开启人脸识别
 */
Device.prototype.faceOn = function(){
    this.changeFaceState("启动人脸识别");
}

/**
 * 关闭人脸识别
 */
Device.prototype.faceOff = function(){
    this.changeFaceState("关闭人脸识别");
}

/**
 * 将状态保存
 */
Device.prototype.changeFaceState = function(option) {
    var that = this;
    var deviceid = this.playInfo.deviceid;
    var type=this.getAttribute().attendance?0:1;
    var soap = new HWSOAP("./facerecognition/optFaceAnaysis.do");
    soap.send({method:option,id:deviceid,type:type},true,function(oResult){
        var result={"state":oResult.result.result.result.errno==0?true:false};
        that.setCurrFaceState(result);
    });
}

Device.prototype.setCurrFaceState = function(result) {
    var re=result.state;
    if(re){
        if(this.playInfo.faceNum){
            $(".face-off", this._html).hide();
            $(".face-on", this._html).show();
            this.playInfo.faceNum = false;
        }else{
            $(".face-on", this._html).hide();
            $(".face-off", this._html).show();
            this.playInfo.faceNum = true;
        }
        application.getHandleClass().postMessage({"id":"MSG_CREATE_GETFACENUM"});
    }
}

Device.prototype.setFaceState = function(result) {
    var re=result.result;
    if(re["人脸识别状态"]&&re["人脸识别状态"]["是否开启"]&&re["人脸识别状态"]["是否开启"]==true){
        $(".face-on", this._html).hide();
        $(".face-off", this._html).show();
        this.playInfo.faceNum = true;
    }else{
        $(".face-off", this._html).hide();
        $(".face-on", this._html).show();
        this.playInfo.faceNum = false;
    }
    application.getHandleClass().postMessage({"id":"MSG_CREATE_GETFACENUM"});
}

/**
 * 停止录像方法
 */
Device.prototype.stopRecord = function() {
    if (!this.playInfo.playurl) {
        return;
    }

    try {
        if (this.playInfo.isrecord == "start") {
            this.plugin.stopRecordVideo();
            $(".stop-record", this._html).hide();
            $(".start-record", this._html).show();
            this.playInfo.isrecord = "stop";
        }
    } catch (e) {
        Device.log("停止录像失败");
    }
}

/**
 * 历史回放改变时间方法
 */
Device.prototype.changeTime = function(milliseconds) {
    var changeTimeInterval = this.playInfo.changeTimeInterval;
    if (changeTimeInterval) {// 如果重新设置慢放速率则取消原来的播放速率
        clearInterval(changeTimeInterval);
    }

    var othis = this;
    var _playInfo = this.playInfo;
    var _comp = this._html;
    milliseconds = milliseconds ? milliseconds : 1000;// 播放速率

    changeTimeInterval = setInterval(function() {
        if (_playInfo.ishistory == "start") {// 是历史播放进度条才向前走
            // 回放的当前时间+1秒
            _playInfo.historydragtime = parseInt(_playInfo.historydragtime) + 1;
            var _dragTime = _playInfo.historydragtime;
            var _startTime = _playInfo.historystarttime;
            var _allTime = _playInfo.historyalltime;
            var _time_width = _dragTime - _startTime;
            var _proportion = _time_width / _allTime;// 当前时间占历史回放总时间的比例

            // 设置历史回放剩余时间
            $(".timetxt", _comp).text(Device.getHistoryTimeText(_allTime - _time_width));

            var _progressbar = $(".progress-bar", _comp);
            var _timebtn = $(".timebtn", _comp);
            _progressbar.width(_proportion * 100 + "%");// 设置进度条
            // 设置进度条上小圆点的位置
            _timebtn.offset({
                left : _progressbar.offset().left + _progressbar.width() - _timebtn.width() / 2
            });

            // 播放到最后6分钟就实时播放
            if (_allTime - _time_width <= _playInfo.historynotdragtime) {
                othis.stopHistory();
                othis.play();
            }
        }
    }, milliseconds);

    this.playInfo.changeTimeInterval = changeTimeInterval;
}

/**
 * 设置播放速度
 */
Device.prototype.setPlaySpeed = function(index) {
    if (!this.playInfo.playurl) {
        return;
    }

    if (this.playInfo.ishistory != "stop") {
        index = index == 0 || index ? index : this.playInfo.slowindex;
        index = index > Device.slow_params.length - 1 ? 2 : index;
        this.playInfo.slowindex = index;
        this.plugin.setPlaySpeedTimes(Device.slow_params[index] + "");
        this.changeTime(1000 / Device.slow_speeds[index]);
        if (this.playInfo.ishistory == "pause") {
            this.pauseHistory();
        }
    }
}

/**
 * 云台转动功能
 */
Device.prototype.controlMove = function(val){
    try {
        this.plugin.ptzControl(val);
    } catch (e) {
        Device.log("云台转动失败");
    }
}



/**
 * 设置播放窗口
 */
Device.prototype.createPlayerWnd = function(width, height, plgWidth, plgHeight) {
    $(this.getHTML()).width(width).height(height);
    var _title = $(".video-title", this._html);
    var _bottom = $(".video-bottom", this._html);
    var _height = height - _title.height() - _bottom.height();

    $(".video-content", this._html).height(_height).width(width);
    $("object", this._html).height(_height).width(width);
    
    try {
    	if (plgWidth == null){
    		plgWidth = width;
    	}
    	if (plgHeight == null){
    		plgHeight = _height;
    	}
    	this.plugin.createPlayerWnd(plgWidth, plgHeight);
        var that = this;
//        setTimeout(function() {
            try {
                var _wndHandle = this.getWndHandle();
                Device.all_devices[_wndHandle] = that;
            } catch (e) {
                Device.log("得到窗口句柄失败");
            }
//        }, 1000);
    } catch (e) {
        Device.log("创建视屏窗口失败");
    }
    
    this.setProgressTimeBtnDrag();
}

/**
 * 修改播放窗口大小
 */
Device.prototype.updateWndSize = function(width, height) {
    $(this.getHTML()).height(height).width(width);
    var _title = $(".video-title", this._html);
    var _bottom = $(".video-bottom", this._html);
    var _height = height - _title.height() - _bottom.height();

    var _content = $(".video-content", this._html);
    var _margin = _content.css("margin-left").replace(/px/,"");
    if(_margin > 0){
        _height = _height - parseInt(_margin) * 2;
        width = width - parseInt(_margin) * 2;
    }
    $(".video-content", this._html).height(_height).width(width);
    $("object", this._html).height(_height).width(width);

    try {
        this.plugin.updateWndSize(width, _height)
    } catch (e) {
        Device.log("改变视屏窗口大小失败");
    }
    this.setProgressTimeBtnDrag();
}

/**
 * 设置object控件高
 */
Device.prototype.setHeight = function(height) {
    var _title = $(".video-title", this._html);
    var _bottom = $(".video-bottom", this._html);
    var _height = height - _title.height() - _bottom.height();

    $(".video-content", this._html).height(_height);
    $("object", this._html).height(_height);
}

/**
 * 设置进度条时间按钮拖拽
 */
Device.prototype.setProgressTimeBtnDrag = function() {
    var othis = this;
    var allTime = this.playInfo.historyalltime;
    var _timebtn = $(".timebtn", this._html);
    var _progress = $("#progress", this._html);

    var _timebtn_width = _timebtn.width();
    var _bar_width = _progress.width();
    var _baroft = _progress.offset();
    var x1 = _baroft.left - _timebtn_width / 2;
    var x2 = _baroft.left + _bar_width - _timebtn_width / 2;

    _timebtn.draggable({
        axis : "x",
        containment : [ x1, 0, x2, 0 ],
        stop : function(event, ui) {
            var _drag_width = _timebtn.offset().left - _progress.offset().left + _timebtn_width / 2;
            var _proportion = _drag_width / _bar_width;

            $(".progress-bar", _progress).width(_proportion * 100 + "%");

            var startTime = othis.playInfo.historystarttime;
            if (othis.playInfo.ishistory == "stop") {
                startTime = Device.getNowTime() - allTime;
            }
            var dragTime = Math.round(allTime * _proportion) + startTime;
            othis.startHistory(startTime, dragTime);
        }
    });
}

/**
 * 全屏方法
 */
Device.prototype.full = function() {
	//全屏时，做报警页面隐藏，当且仅当根页面有此消息时才能抛出此消息，防止其他视频页面全屏影响报警页面的地图显示
	var messageObj = application._handleClass._oMsgH;
	var flag = false;
	for(var message in messageObj){
		if("MSG_DEVICE_FULL" == message){
			flag = true;
			break;
		}
	}
	if(flag){
		application.getHandleClass().postMessage({"id":"MSG_DEVICE_FULL", control:this});
	}
    this._videoParent = $(this._html).parent();

    var _html = $(this._html);
    var _width = document.documentElement.clientWidth;
    var _height = document.documentElement.clientHeight;
    var _left = "5px";
    var _top = "5px";
    var _zindex = 9999;

    if(this.playInfo.ocontrol){
        var _control = $(this.playInfo.ocontrol);
        _width = _control.width();
        _height = _control.height();
        var offset = _control.offset();
        _left = offset.left;
        _top = offset.top;
        _zindex = 100;
    }

    // 全屏时显示慢放按钮
    $(".video-bottom-middle", this._html).show();
    if (this.playInfo.ishistory == "start") {
        $(".slow", this._html).show();
    }

    if ($("#" + this.getAttribute().id, ".modal-dialog").length > 0) {
        var that = this;
        $(".modal-dialog").each(function(e) {
            if ($("#" + that.getAttribute().id, this).length > 0) {
                _width = $(this).width();
                _height = $(this).height();
            }
        });
    }

    // 先把所有视频控件高度变成0，避免全屏窗口还能看到这些控件的画面
    $(".video-content").each(function(e) {
        $("object", this).height(0).width(0);
    });

    //将所有可视对讲空间高度变成0,避免浮在视屏上面
    $(".monitor-body").each(function(e){
        $("object",this).height(0);
    });

    // 停止来帮监听，避免画中画现象
    /*$(".monitor-body").each(function(e) {
        Monitor.listenStopByObj(this);
    });*/

    this.oldCss = {
        "position" : _html.css('position'),
        "left" : _html.css('left'),
        "top" : _html.css('top'),
        "width" : _html.css('width'),
        "height" : _html.css('height'),
        "z-index" : 100
    };

    var _newcss = {
        "position":"fixed",
        "left":_left,
        "top":_top,
        "z-index":_zindex
    };
    _html.css(_newcss);
    //放在body上
//    _html.detach();
//    $("body").append(_html);

    this.clickSlowBtn(true);
    if (this.checkBrower() == "Safari"){
    	//处理QT上视频 全屏出现白边的情况
    	this.updateWndSize(_width - 10, _height + 10);
    } else {
    	this.updateWndSize(_width - 10, _height - 10);
    }

    var _timebtn = $(".timebtn", _html);
    var _progress_bar = $(".progress-bar", _html);
    _timebtn.offset({
        left : _progress_bar.offset().left + _progress_bar.width() - _timebtn.width() / 2
    });

    $(".video-del", _html).hide();
    $(".full", _html).hide();
    $(".nofull", _html).show();
    $(".home-header").css("z-index", "-1");
    $("#progress", this._html).removeClass("progress-nofull");

    this.playInfo.isfull = true;

    // 在qt上特殊处理
    if(typeof(g_sSession) != "undefined"){
        qtwebobject.exec("special_esc" , 4);
    }
    
    application.getHandleClass().postMessage({"id":"MSG_DEVICE_FULLOVER", control:this});
}

/**
 * 隐藏全屏按钮
 */
Device.prototype.hideFull = function () {
    $(".full",this.getHTML()).hide();
}

Device.prototype.checkBrower = function(){
	var userAgent = navigator.userAgent; // 取得浏览器的userAgent字符串
	var isOpera = userAgent.indexOf("Opera") > -1;
	if (isOpera) {
		return "Opera"
	}
	; // 判断是否Opera浏览器
	if (userAgent.indexOf("Firefox") > -1) {
		return "FF";
	} // 判断是否Firefox浏览器
	if (userAgent.indexOf("Chrome") > -1) {
		return "Chrome";
	}
	if (userAgent.indexOf("Safari") > -1) {
		return "Safari";
	} // 判断是否Safari浏览器
	if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1
			&& !isOpera) {
		return "IE";
	}// 判断是否IE浏览器
}

/**
 * 退出全屏方法
 */
Device.prototype.nofull = function(src) {
	//当且仅当根页面有MSG_DEVICE_NOFULL此消息时，才能做此操作
	var messageObj = application._handleClass._oMsgH;
	var flag = false;
	for(var message in messageObj){
		if("MSG_DEVICE_FULL" == message){
			flag = true;
			break;
		}
	}
	if(flag){
		application.getHandleClass().postMessage({"id":"MSG_DEVICE_NOFULL"});
	}
    var _html = $(this._html);
    var _width = this.oldCss.width.replace("px", "");
    var _height = this.oldCss.height.replace("px", "");
    _html.css(this.oldCss);
    $(".full", _html).show();
    $(".nofull", _html).hide();
    $(".home-header").css("z-index", "1000");
    $("#progress", this._html).addClass("progress-nofull");

    if (this.playInfo.hidedel != true) {
        $(".video-del", _html).show();
    }
    if (this.playInfo.hidetimeline) {
        $(".video-bottom-middle", this._html).hide();
    }
    if(this.playInfo.hideslowbtn){
        $(".slow", this._html).hide();
    }

    this.clickSlowBtn(true);
    this.updateWndSize(_width, _height);

    //返回原位
//    _html.detach();
//    $(this._videoParent).append(_html);

    var _timebtn = $(".timebtn", _html);
    var _progress_bar = $(".progress-bar", _html);
    _timebtn.offset({
        left : _progress_bar.offset().left + _progress_bar.width() - _timebtn.width() / 2
    });

    // 显示其他视频
    $(".video-content").each(function(e) {
        var _this = $(this);
        $("object", this).height(_this.height()).width(_this.width());
    });

    // 显示可视对讲窗口
    $(".monitor-body").each(function(e){
        var _this = $(this);
        $("object", this).height(_this.height()-66);
    });
    
    this.playInfo.isfull = false;
    
    // 在qt上特殊处理
    if(typeof(g_sSession) != "undefined"){
        qtwebobject.exec("general_esc" , 4);
    }
}

/**
 * 点击视频慢放按钮
 */
Device.prototype.clickSlowBtn = function(isHidden) {
    var _slow_btm = $(".video-slow-bottom", this._html);
    var _slow = $(".slow", this._html);
    var _ch = $(this._html).height();
    var _sh = _slow_btm.height();

    if (_slow.attr("show") == "true" || isHidden == true) {
        this.setHeight(_ch);
        _slow.css("color", "white");
        _slow.attr('show', 'false');
        _slow_btm.hide();
    } else {
        this.setHeight(_ch - _sh);
        _slow.css("color", "red");
        _slow.attr('show', 'true');
        _slow_btm.show();

        this.setSlowTimeBtnDrag();
    }
}

/**
 * 显示云台功能
 */
Device.prototype.clickConsoleBtn = function(){
    var _html = $(this.getHTML());
    if(this.playInfo.isconsole != true){
        $(".control-direction",this._html).show();
        $(".control",this._html).addClass("control-select");
        $(".video-content",this._html).css("margin","30px")
        this.playInfo.isconsole = true;
    }else{
        $(".control-direction",this._html).hide();
        $(".control",this._html).removeClass("control-select");
        $(".video-content",this._html).css("margin","0px")
        this.playInfo.isconsole = false
    }
    this.updateWndSize(_html.width(),_html.height());
}

/**
 * 设置慢放按钮拖拽
 */
Device.prototype.setSlowTimeBtnDrag = function() {
    var othis = this;
    var _slowline = $(".slowline", this._html);
    var _slowbtn = $(".slowbtn", this._html);
    var _width = _slowline.width();
    var _slowline_oft = _slowline.offset();
    var x1 = _slowline_oft.left - _slowbtn.width() / 2;
    var x2 = _slowline_oft.left + _slowline.width() - _slowbtn.width() / 2;

    _slowbtn.draggable({
        containment : [ x1, 0, x2, 0 ],
        axis : "x",
        grid : [ 44, 0 ],
        stop : function(event, ui) {
            var _move_width = _slowbtn.offset().left + _slowbtn.width() / 2 - _slowline.offset().left;
            var _one_width = _width / (Device.slow_params.length - 1);
            var _index = Math.round(_move_width / _one_width);
            othis.setPlaySpeed(_index);
        }
    });
}

/**
 * 初始化设置摄像头播放基本信息
 */
Device.prototype.initInfo = function() {

}

/**
 * 设置摄像头的播放信息
 */
Device.prototype.setPlayInfo = function(value) {
    if (value["deviceid"] != undefined) {
        this.playInfo.deviceid = value["deviceid"];
    }
    if (value["playurl"] != undefined) {
        this.playInfo.playurl = value["playurl"];
    }
    if (value["hidedel"] != undefined) {
        this.playInfo.hidedel = value["hidedel"] == 'true' || value["hidedel"] == true;
    }
    if (value["hidetimeline"] != undefined) {
        this.playInfo.hidetimeline = value["hidetimeline"] == 'true' || value["hidetimeline"] == true;
    }
    if (value["hideslowbtn"] != undefined) {
        this.playInfo.hideslowbtn = value["hideslowbtn"] == 'true' || value["hideslowbtn"] == true;
    }
    if (value["ocontrol"] != undefined) {
        this.playInfo.ocontrol = value["ocontrol"];
    }
    this.playInfo.titlename = value["titlename"] ? value["titlename"] : "";
    this.playInfo.isfull = value["isfull"] == 'true' || value["isfull"] == true;
    this.setHistoryStartTime(value["historystarttime"]);
    this.setHistoryAllTime(value["historystarttime"] , value["historyendtime"]);
    
    $(".video-name", this._html).attr('title', this.playInfo.titlename).text(this.playInfo.titlename);

    // 屏蔽录像
    //$('.start-record', this._html).remove();
    //$('.stop-record', this._html).remove();

    if (this.playInfo.hidedel) {
        $(".video-del", this._html).hide();
    }
    if (this.playInfo.hidetimeline) {
        $(".video-bottom-middle", this._html).hide();
    }
    if(this.playInfo.hideslowbtn){
        $(".slow", this._html).hide();
    }

    if (this.playInfo.isfull) {
        $(".full", this._html).hide();
        $(".nofull", this._html).show();
        $("#progress", this._html).removeClass("progress-nofull");
    }

    if (value["notimetxt"] == "true" || value["notimetxt"] == true) {
        $(".timetxt", this._html).remove();
    }
    this.playInfo.sessionid = JSON.stringify(this.getVideoParam(this.playInfo.deviceid));
}

Device.prototype.getVideoParam = function(id) {
    if (!id) return "";
    var soap = new HWSOAP("/videomonitor/getVideoParam.do");
    soap.send({id:id});
    var result = soap.getResult();
    this.setFaceState(result);
    return result.result["参数表"];
}

/**
 * 初始化布局(小屏时可以使用)
 */
Device.prototype.initLayout = function() {
    
    var $html = this._html;
    var _right = $(".video-bottom-right", $html).width();
    $(".video-bottom-middle", $html).css("margin-right", _right + 70 + "px");
}

Device.prototype.customDeviceLayout = function (params) {
    
}

/**
 * 绑定页面销毁事件
 */
Device.bindWindowDestroy = function(_window) {
    $(_window).bind('beforeunload', function() {
        $("body").find(".video-comp").each(function() {
            Device.delVideoByObj(this);
        });
    });
}

/**
 * 设置摄像头的播放信息
 */
Device.prototype.saveLog = function(value) {
    var soap = new HWSOAP("./videomonitor/videoOperLog.do");
    soap.send({
        params : JSON.stringify(value)
    });
}

/**
 * 播放摄像头
 */
Device.prototype.setValue = function(value, data, unCreateWnd) {
    if (value == "")
        return;
    if (data.id == "")
        return;
    this.stop();
    var _obj = $(this.getHTML());
    data.playurl = value;
    data.deviceid = data.id;
    data.titlename = data.name;
    this.setPlayInfo(data);

    if (!unCreateWnd) {
        this.createPlayerWnd(_obj.width(), _obj.height());
    }
    this.initLayout();
    if (data.playhistory) {
        this.startHistory(this.playInfo.historystarttime, this.playInfo.historystarttime);
    } else {
        if(!(data.autoplay == false || data.autoplay == "false")){
            this.play();
        }
    }
}

Device.prototype.getValue = function() {
	return this.playInfo.playurl;
}

Device.prototype.getPlayInfo = function() {
	return this.playInfo;
}
	
/**
 * 设置历史播放开始时间
 */
Device.prototype.setHistoryStartTime = function(historyStartTime) {
    if (historyStartTime) {
        historyStartTime = historyStartTime + "";
        if (/^\d+$/.test(historyStartTime)) {
            historyStartTime = historyStartTime.replace(/^(\d{10})\d*/, "$1");
        } else if (/\d{4}-\d{2}-\d{2}/.test(historyStartTime)) {
            historyStartTime = Device.getTime(historyStartTime);
        }
        this.playInfo.historystarttime = parseInt(historyStartTime);
        this.playInfo.historydragtime = this.playInfo.historystarttime;
    }
}

/**
 * 设置历史播放总时间
 */
Device.prototype.setHistoryAllTime = function (historyStartTime, historyEndTime) {
    if(historyStartTime && !historyEndTime){
        historyEndTime = Device.getNowTime();
    }
    
    if (historyEndTime) {
        historyEndTime = historyEndTime + "";
        if (/^\d+$/.test(historyEndTime)) {
            historyEndTime = historyEndTime.replace(/^(\d{10})\d*/, "$1");
        } else if (/\d{4}-\d{2}-\d{2}/.test(historyEndTime)) {
            historyEndTime = Device.getTime(historyEndTime);
        }
        this.playInfo.historyalltime = parseInt(historyEndTime) - this.playInfo.historystarttime;
        
        var _nowdate = Device.getNowTime();
        var _time = _nowdate - parseInt(historyEndTime);
        // 如果差值是大于等于6分钟的那么就都可以放
        // 如果差值小于6分钟那么差值不能放
        this.playInfo.historynotdragtime = _time > this.playInfo.historydefaultnotdragtime ? 0 : this.playInfo.historydefaultnotdragtime - _time;
    }
}

/**
 * 得到服务器现在时间(秒)
 */
Device.getNowTime = function() {
    var _date = DateTime.getDateTime();
    return Device.getTime(_date);
}

/**
 * 得到时间(秒)
 */
Device.getTime = function(time) {
    var _year = time.substring(0, 4) - 0;
    var _month = time.substring(5, 7) - 1;
    var _day = time.substring(8, 10) - 0;
    var _hour = time.substring(11, 13) - 0;
    var _minute = time.substring(14, 16) - 0;
    var _second = time.substring(17, 19) - 0;

    var _date = new Date(_year, _month, _day, _hour, _minute, _second);

    return Math.round(_date.getTime() / 1000);
}

/**
 * 打印日志
 */
Device.log = function(value) {
    if (typeof(console) != 'undefined') {
        console.log(value);
    }
}

/**
 * 得到历史回放剩余时间
 */
Device.getHistoryTimeText = function(time) {
    var _time_h = Math.floor(time / 3600);
    var _time_m = Math.floor(time % 3600 / 60);
    var _time_s = time % 60;
    var _timeTxt = _time_h < 10 ? "0" + _time_h : "" + _time_h;
    _timeTxt += ":";
    _timeTxt += _time_m < 10 ? "0" + _time_m : "" + _time_m;
    _timeTxt += ":";
    _timeTxt += _time_s < 10 ? "0" + _time_s : "" + _time_s;

    return "-" + _timeTxt;
}

/**
 * 双击视频插件回调方法
 */
function firBreathCallBack(param){
    var _params = param.split(";");
    var _wndHandle = _params[0];
    var _order = _params[1];
    
    var _devices = Device.all_devices[_wndHandle];
    if(_devices.playInfo.isfull){
        _devices.nofull();
    }else{
        _devices.full();
    }
}
